package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    // 获取openId的接口路径
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    /**
     * 获取openId
     *
     * @param code 小程序端传递的code
     * @return openId
     */
    @Override
    public String getOpenId(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("js_code", code);

        String result = HttpUtil.get(REQUEST_URL, paramMap);
        // 将结果字符串转换为JSON对象
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 判断结果是失败的
        // 如果errcode不为空，说明获取失败
        if (!ObjectUtils.isEmpty(jsonObject.getInt("errcode"))) {
            throw new BaseException("获取openId失败", jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }

    /**
     * 获取手机号码
     *
     * @param phoneCode 小程序端传递的phoneCode
     * @return 手机号
     */
    @Override
    public String getPhoneNumber(String phoneCode) {
        String accessToken = getAccessToken();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", phoneCode);
        String result = HttpUtil.post(PHONE_REQUEST_URL + accessToken, JSONUtil.toJsonStr(paramMap));

        // 解析结果为JSON对象
        JSONObject jsonObject = JSONUtil.parseObj(result);

        // 判断请求是否成功
        if (!jsonObject.getInt("errcode").equals(0)) {
            throw new BaseException("获取手机号失败", jsonObject.getStr("errmsg"));
        }

        // 成功，获取手机号返回
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    /**
     * 获取accessToken
     * @return accessToken
     */
    private String getAccessToken() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);

        String result = HttpUtil.get(TOKEN_URL, paramMap);

        // 将字符串解析为JSON对象
        JSONObject jsonObject = JSONUtil.parseObj(result);
        return jsonObject.getStr("access_token");
    }
}
